package com.example.qq.gps;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.Image;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.example.qq.Diy.MyToast;
import com.example.qq.Diy.Titanic;
import com.example.qq.Diy.TitanicTextView;
import com.example.qq.R;
import com.example.qq.The_Main_Main_Ui;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Gps extends AppCompatActivity {
    public LocationClient mlocationClient;
    private static TextView textView;
    public Button button,button1;
    public static String dizhi,difang="";


    private static String path = "https://www.apiopen.top/weatherApi?city=";
    public static List list = new ArrayList<Message>();
    public static String diqu ;
    public static String ganmao,jiedao ;
    public  static TextView fengxiang,fengli,textdiqu,textdifang,texttype;
    public static TextView textriqi1,textwendu1;
    public ImageView textimg1;

    public static TextView textriqi2,textwendu2;
    public ImageView textimg2;

    public static TextView textriqi3,textwendu3;
    public ImageView textimg3;

    public static TextView textriqi4,textwendu4;
    public ImageView textimg4;

    public static TextView textriqi5,textwendu5;
    public ImageView textimg5;
    public TitanicTextView titanic ;
    public TextView textganmao;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mlocationClient = new LocationClient(getApplicationContext());
        mlocationClient.registerLocationListener(new My());
        setContentView(R.layout.activity_gps);
        textView = (TextView)findViewById(R.id.web111);
        fengxiang = (TextView)findViewById(R.id.fengxiang);
        fengli = (TextView)findViewById(R.id.fengli);
        textdiqu=(TextView)findViewById(R.id.textdiqu);
        textdifang=(TextView)findViewById(R.id.textlu);
        texttype=(TextView)findViewById(R.id.texttype);
        textriqi1=(TextView)findViewById(R.id.textriqi1);
        textwendu1=(TextView)findViewById(R.id.textwendu1);
        textimg1 =(ImageView) findViewById(R.id.textimg1);

        textriqi2=(TextView)findViewById(R.id.textriqi2);
        textwendu2=(TextView)findViewById(R.id.textwendu2);
        textimg2 =(ImageView) findViewById(R.id.textimg2);

        textriqi3=(TextView)findViewById(R.id.textriqi3);
        textwendu3=(TextView)findViewById(R.id.textwendu3);
        textimg3 =(ImageView) findViewById(R.id.textimg3);

        textriqi4=(TextView)findViewById(R.id.textriqi4);
        textwendu4=(TextView)findViewById(R.id.textwendu4);
        textimg4 =(ImageView) findViewById(R.id.textimg4);

        textriqi5=(TextView)findViewById(R.id.textriqi5);
        textwendu5=(TextView)findViewById(R.id.textwendu5);
        textimg5 =(ImageView) findViewById(R.id.textimg5);

         titanic =(TitanicTextView)findViewById(R.id.wendu);
         textganmao=(TextView)findViewById(R.id.textganmao);
        button = (Button)findViewById(R.id.WEB);
        button1=(Button)findViewById(R.id.MAP);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Gps.this,Map.class);
                startActivity(intent);
            }
        });
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                start();
              try {
                  sendRecoudeOkhttp();
                  Message message = (Message) list.get(0);
                  Log.d("Gps",message.getFengxiang());
                  fengxiang.setText(message.getFengxiang());
                  fengli.setText(message.getFengli());
                  textdiqu.setText(diqu);
                  textdifang.setText(difang);
                  texttype.setText(message.getTianqi());

                     Message message1 = (Message) list.get(0);
                     textriqi1.setText(message1.getRiqi()+"●"+message1.getTianqi());
                     textwendu1.setText(message1.diwen+"/"+message1.getGaowen()+"℃");
                     if(message1.getTianqi().equals("晴"))
                     {
                         textimg1.setImageResource(R.drawable.qing);
                     }
                     else if(message1.getTianqi().equals("阴"))
                  {
                      textimg1.setImageResource(R.drawable.yin);
                  }
                 else if(message1.getTianqi().equals("多云"))
                  {
                      textimg1.setImageResource(R.drawable.duoyun);
                  }else
                     {
                         textimg1.setImageResource(R.drawable.yu);
                     }

                  Message message2 = (Message) list.get(1);
                  textriqi2.setText(message2.getRiqi()+"●"+message2.getTianqi());
                  textwendu2.setText(message2.diwen+"/"+message2.getGaowen()+"℃");
                  if(message2.getTianqi().equals("晴"))
                  {
                      textimg2.setImageResource(R.drawable.qing);
                  }
                  else if(message2.getTianqi().equals("阴"))
                  {
                      textimg2.setImageResource(R.drawable.yin);
                  }
                  else if(message2.getTianqi().equals("多云"))
                  {
                      textimg2.setImageResource(R.drawable.duoyun);
                  }else
                  {
                      textimg2.setImageResource(R.drawable.yu);
                  }




                  Message message3 = (Message) list.get(2);
                  textriqi3.setText(message3.getRiqi()+"●"+message3.getTianqi());
                  textwendu3.setText(message3.diwen+"/"+message3.getGaowen()+"℃");
                  if(message3.getTianqi().equals("晴"))
                  {
                      textimg3.setImageResource(R.drawable.qing);
                  }
                  else if(message3.getTianqi().equals("阴"))
                  {
                      textimg3.setImageResource(R.drawable.yin);
                  }
                  else if(message3.getTianqi().equals("多云"))
                  {
                      textimg3.setImageResource(R.drawable.duoyun);
                  }else
                  {
                      textimg3.setImageResource(R.drawable.yu);
                  }




                  Message message4 = (Message) list.get(3);
                  textriqi4.setText(message4.getRiqi()+"●"+message4.getTianqi());
                  textwendu4.setText(message4.diwen+"/"+message4.getGaowen()+"℃");
                  if(message4.getTianqi().equals("晴"))
                  {
                      textimg4.setImageResource(R.drawable.qing);
                  }
                  else if(message4.getTianqi().equals("阴"))
                  {
                      textimg4.setImageResource(R.drawable.yin);
                  }
                  else if(message4.getTianqi().equals("多云"))
                  {
                      textimg4.setImageResource(R.drawable.duoyun);
                  }else
                  {
                      textimg4.setImageResource(R.drawable.yu);
                  }


                  Message message5 = (Message) list.get(4);
                  textriqi5.setText(message5.getRiqi()+"●"+message5.getTianqi());
                  textwendu5.setText(message5.diwen+"/"+message5.getGaowen()+"℃");
                  if(message5.getTianqi().equals("晴"))
                  {
                      textimg5.setImageResource(R.drawable.qing);
                  }
                  else if(message5.getTianqi().equals("阴"))
                  {
                      textimg5.setImageResource(R.drawable.yin);
                  }
                  else if(message5.getTianqi().equals("多云"))
                  {
                      textimg5.setImageResource(R.drawable.duoyun);
                  }else
                  {
                      textimg5.setImageResource(R.drawable.yu);
                  }


                  titanic.setText((CharSequence) message1.getGaowen());
                  textganmao.setText(ganmao);
              }catch (Exception e)
              {
                  e.printStackTrace();
              }
                Toast.makeText(Gps.this,"已刷新",Toast.LENGTH_SHORT).show();
            }
        });
        List<String> list = new ArrayList<>();
        if(ContextCompat.checkSelfPermission(Gps.this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
              list.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if(ContextCompat.checkSelfPermission(Gps.this,Manifest.permission.READ_PHONE_STATE)!=PackageManager.PERMISSION_GRANTED){
            list.add(Manifest.permission.READ_PHONE_STATE);
        }
        if(ContextCompat.checkSelfPermission(Gps.this,Manifest.permission.WRITE_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED){
            list.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        if(!list.isEmpty())
        {
            String[] List = list.toArray(new String[list.size()]);
            ActivityCompat.requestPermissions(Gps.this,List,1);
        }else
        {
          start();

        }
        TitanicTextView tv = (TitanicTextView) findViewById(R.id.wendu);

        // set fancy typeface

        // start animation
        new Titanic().start(tv);
    }
    private void start(){
        shuaxin();
        mlocationClient.start();
    }
    private void shuaxin(){
        LocationClientOption option = new LocationClientOption();
        option.setScanSpan(5000);
        option.setIsNeedAddress(true);
        mlocationClient.setLocOption(option);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mlocationClient.stop();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode)
        {
            case 1:
                if(grantResults.length>0){
                    for (int result : grantResults)
                    {
                        if(result!=PackageManager.PERMISSION_GRANTED){
                            MyToast.DiyToast(Gps.this,"必须授权所有权限才可以使用GPS！");
//                            finish();
                            startActivity(new Intent(Gps.this, The_Main_Main_Ui.class));
                            return;
                        }
                    }
                    start();
                }else
                {
                    Toast.makeText(Gps.this,"发生未知的错误！",Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;

                default:
        }
    }
    public static class My implements BDLocationListener{

        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            StringBuilder d = new StringBuilder();
            StringBuilder c =new StringBuilder();
            d.append("纬度：").append(bdLocation.getLatitude()).append("\n");
            d.append("经度：").append(bdLocation.getLongitude()).append("\n");
            d.append("国家：").append(bdLocation.getCountry()).append("\n");
            d.append("省份：").append(bdLocation.getProvince()).append("\n");
            c.append(bdLocation.getProvince());
            d.append("市区：").append(bdLocation.getCity()).append("\n");
            diqu=bdLocation.getCity().toString();
            c.append(bdLocation.getCity());
            d.append("地区：").append(bdLocation.getDistrict()).append("\n");
            path=path+bdLocation.getDistrict().toString();
            difang =bdLocation.getDistrict().toString();
            c.append(bdLocation.getDistrict());
            d.append("街道：").append(bdLocation.getStreet()).append("\n");
            jiedao=bdLocation.getStreet();
            c.append(bdLocation.getStreet());
            dizhi=c.toString();
            d.append("定位方式：");
            if(bdLocation.getLocType()==BDLocation.TypeGpsLocation){
                d.append("gg");
            }else if(bdLocation.getLocType()==BDLocation.TypeNetWorkLocation)
            {
                d.append("网络");
            }else
                d.append("未知");
            textView.setText(d);

        }
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
             Intent intent =new Intent();
             intent.putExtra("data_return",difang);
             setResult(RESULT_OK,intent);
             finish();
        }
        return true;
    }






    public void sendRecoudeOkhttp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(path)
                            .build();
                    Log.d("Gps",path);
                    Response response = client.newCall(request).execute();
                    String r = response.body().string();
                    parse(r);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void parse(String JsonMessage) {
        try {
            JSONObject jsonObject1 = new JSONObject(JsonMessage);
            JSONObject t = (JSONObject) jsonObject1.get("data");
            diqu = t.getString("city").toString();
            ganmao = t.getString("ganmao").toString();
            Log.d("TheMainUi",diqu);
            JSONArray array = t.getJSONArray("forecast");
            for (int b = 0; b < array.length(); b++) {
                JSONObject jsonObject = (JSONObject) array.get(b);
                Message message = new Message();
                message.riqi = jsonObject.getString("date").toString();
                String a=jsonObject.getString("high").toString();
                String regEx="[^0-9]";
                Pattern p = Pattern.compile(regEx);
                Matcher m = p.matcher(a);
                message.gaowen = m.replaceAll("").trim();
                Log.d("Gps",message.gaowen);
                message.fengli = jsonObject.getString("fengli").toString();
                String b1=jsonObject.getString("low").toString();
                String regEx1="[^0-9]";
                Pattern p1 = Pattern.compile(regEx1);
                Matcher m1 = p1.matcher(b1);
                message.diwen = m1.replaceAll("").trim();
                Log.d("Gps",message.diwen);
                message.fengxiang = jsonObject.getString("fengxiang").toString();
                message.tianqi = jsonObject.getString("type").toString();
                list.add(message);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.d("Gps", String.valueOf(list.size()));
    }

    public String getListSize()

    {
        return String.valueOf(this.list.size());
    }

}
